package com.qf.cx.simplenms.webservice.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qf.cx.simplenms.persist.entity.SubscriberEntity;
import com.qf.cx.simplenms.persist.service.api.SubscriberService;
import com.qf.cx.simplenms.webservice.model.Subscriber;

@RestController
@RequestMapping(path = "/subscribers")
public class SubscirberController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SubscriberService subscriberService;

	@RequestMapping(method = RequestMethod.GET)
	public List<Subscriber> getSubscribers() {
		List<SubscriberEntity> sbs = subscriberService.getSubscribers();
		List<Subscriber> list = new ArrayList<>();
		sbs.forEach(t -> list.add(Subscriber.from(t)));
		return list;
	}

	@RequestMapping(method = RequestMethod.POST)
	public void addSubscribers(@RequestBody List<Subscriber> subscribers) {
		logger.debug("add subscribers {}", subscribers);
		List<SubscriberEntity> subscriberEntities = new ArrayList<>(subscribers.size());
		subscribers.forEach(t -> subscriberEntities.add(t.toSubscriberEntity()));
		subscriberService.addSubscribers(subscriberEntities);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public void updateSubscriber(@PathVariable("id") long id, @RequestBody Subscriber subscriber) {
		logger.debug("update subscriber {}", subscriber);
		SubscriberEntity subscriberEntity = subscriber.toSubscriberEntity();
		subscriberService.updateSubscriber(subscriberEntity);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public void deleteSubscriber(@PathVariable("id") long id) {
		logger.debug("delete subscriber {}", id);
		subscriberService.deleteSubscriber(id);
	}

}